<?php
namespace Home\Controller;
use Think\Controller;
/**
* 人脸识别
*/
class FaceController extends Controller{

	//服务器调用地址
	protected $apiurl = 'https://api-cn.faceplusplus.com/facepp/v3/compare';
	//用户名
	protected $api_key = 'hBRU6CDxwibQmfqgQ0da60LheNBiRkWa';
	//密码
	protected $api_secret = '8jGs_hR6Yffgpdj4JnGUZ-9QhH8arj-I';
	//头像存放地址
	protected $filepath = './img/';
	//头像存放名字
	protected $filename = '808.jpg';

	/**
	* 人脸识别
	*/
	public function index($image=''){

    	$url = $this->apiurl;
    	$data = array(
	        'api_key'=>$this->api_key,
	        'api_secret'=>$this->api_secret,
	        'image_url1'=>'http://www.next.zm-idea.com/Public/Uploads/active/911491058138.jpg',
	        'image_url2'=>'http://wx.qlogo.cn/mmopen/Iv8D5nD32icIFAmMo47ibhtxEJuYxPSdsGHrrbdPH6DIAQlYXCrHehjP5fDJGPxIrH6ict5XyeCxXIRpiaayMJROQg/0'
	    );

	    $res = curlGet($url,$data);
	    dump(json_decode($res));exit();
	    $res = json_decode($res)->error_message;
	    dump($res);exit();
	}

	// 获取face token
	public function facegetToken(){

		$user_id = get_user();
		$this->error_auths($user_id,'a');
		$this->error_auths($user_id,'b');
		$image = I('post.image') ? I('post.image') : $this->ajaxReturn(is_not('image/必须'));
		// $images = A('Photo')->addImg($image);
		// $image_url = 'http://'.C('INT_COM').$images;
		$image_url = $image;
		// $image_url = 'http://www.next.zm-idea.com/Public/Uploads/active/Wx_Image1161496131836.jpeg';
		// \Think\Log::record($image_url);
		//检测看看有没有设置了faceset token
		$is_token = M('user')->where(array('id'=>$user_id))->getField('face_token');

		//检测看看有没有注册过人脸
		$is_auth = M('face_config')->select();
		if (count($is_auth) >4) 
		{
			$this->ajaxReturn(is_not('请联系开发人员'));
		}
		if ($is_auth) {
			foreach ($is_auth as $k => $v) {
				$is_auth_set = $this->faceauths1($image_url,$v['faceset']);
				if ($is_auth_set == 101) 
				{	
					// if (!$is_token) 
					// {
						$this->error_auth($user_id,'b');
						$this->ajaxReturn(is_not('提交失败!该人脸已被注册'));
					// }
				}else if($is_auth_set == 100){
					$is_auth_set = 'ok';
				}else{
					$this->error_auth($user_id,'a');
					$this->ajaxReturn(is_not('提交失败!'.$is_auth_set));
				}
				
			}
		}

		// 检测是否需要新建一个faceset
		$faceset_token = M('face_config')->order('id desc')->where(array('num'=>array('gt',0)))->find();
		if(!$faceset_token)
		{
			$type = 2;
		}else{
			if ($faceset_token['num'] == 980 && $is_token) {//防止刚刚好980 是第二张图片认证的存到第二个faceset
				$type = 1;
			}else{

				if ($faceset_token['num']<980) 
				{
					$type = 1;
				}else{
					$type = 2;
				}
			}
		}
		// $image_url='http://www.next.zm-idea.com/Public/Uploads/weixin/Wx_Image1311494520897.jpeg';


		$url = 'https://api-cn.faceplusplus.com/facepp/v3/detect';
    	$data = array(
	        'api_key'=>$this->api_key,
	        'api_secret'=>$this->api_secret,
	        'image_url' => $image_url,
	    );

	    $res = curlGet($url,$data);// face++
	    $res = json_decode($res);
	    
	    $token = $res->faces[0]->face_token;
	    // \Think\Log::record($token.'renlian');
	    if (!$token) 
	    {	
	    	$this->error_auth($user_id,'b');
	    	$this->ajaxReturn(is_not('请上传人脸图!!'));
	    }
	    $error_message = $res->error_message;

	    if (!$error_message) 
	    {	
	    	// 如果没有is_token 说明是第一张图片，要加入faceset ，有如果有，就是第二张图片，不加入faceset
	    	
	    	if ($type ==1) {
	    		$this ->addFacesetToken($token);
	    	}else{
	    		$this ->facesetToken($token);
	    	}
    	
	    	$this ->add_auth($image_url);
	    	$result["result"] = true;
			$result['message'] = "提交成功";
			$result['token'] = $token;
			$this->ajaxReturn($result);
	    }else
	    {	
	    	$this->error_auth($user_id,'a');
	    	$this->ajaxReturn(is_not('提交失败!请重试:'.$error_message));
	    }
	}

	//设置 face token 组，faceset_token
	public function facesetToken($token){
		$user_id = get_user();
		$url = 'https://api-cn.faceplusplus.com/facepp/v3/faceset/create';

    	$data = array(
	        'api_key'=>$this->api_key,
	        'api_secret'=>$this->api_secret,
	        'face_tokens' => $token,
	    );

	    $res = curlGet($url,$data);
	    $res = json_decode($res);
	    $faceset_token = $res->faceset_token;
	    // dump($res);exit();

	    $error_message = $res->error_message;

	    if ($error_message) 
	    {	
	    	$this->ajaxReturn(is_not('提交失败!请重试'.$error_message));
	    	return false;
	    }
	    $config = array(
	    	'faceset'  => $faceset_token,
	    	'num'      => 1,
	    	);
	    $faceset_token_id = M('face_config')->add($config);

	    M('user')->where('id='.$user_id)->save(array('face_token'=>$token,'faceset_token_id'=>$faceset_token_id,'is_verify'=>'1'));
	    
	    return true;

	}

	// 向faceset_token 组加 face_token
	public function addFacesetToken($token){
		$user_id = get_user();
		// $this->ajaxReturn(is_not($user_id));
		// $facesetToken = M('user')->where(array('id'=>$user_id))->getField('face_token');
		// $this->ajaxReturn(is_not($facesetToken));
		$faceset = M('face_config')->where(array('num'=>array('gt',0)))->order('id desc')->field('faceset,id')->find();
		$facesetToken = $faceset['faceset'];
		$faceset_token_id = $faceset['id'];

		$url = 'https://api-cn.faceplusplus.com/facepp/v3/faceset/addface';

    	$data = array(
	        'api_key'=>$this->api_key,
	        'api_secret'=>$this->api_secret,
	        'face_tokens' => $token,
	        'faceset_token' => $facesetToken,
	    );

	    $res = curlGet($url,$data);
		// dump(json_decode($res));exit();
	    $error_message = json_decode($res)->error_message;
	    if ($error_message) 
	    {	
	    	$this->ajaxReturn(is_not('提交失败!请重试'.$error_message));
	    	return false;
	    }
	    M('user')->where(array('id'=>$user_id))->save(array('face_token'=>$token,'faceset_token_id'=>$faceset_token_id));
	    M('face_config')->where(array('id'=>$faceset_token_id))->setInc('num',1);
	    return true;

	}

	// faceset_token 对比
	public function faceauths1($image,$token){
		
    	$url = 'https://api-cn.faceplusplus.com/facepp/v3/search';

    	$data = array(
	        'api_key'       => $this->api_key,
	        'api_secret'    => $this->api_secret,
	        'image_url'     => $image,
	        'faceset_token' => $token,
	        // 'image_base64'  => $image,
	    );

	    $res = curlGet($url,$data);
	    $res = json_decode($res);
	    // dump($res);exit();
	    $error_message = $res->error_message;
	    if ($error_message) 
	    {	
	    	return $error_message;
	    	$this->ajaxReturn(is_not('网络出错'.$error_message));
	    }
	    $istrue = $res->results[0]->confidence;
	    $intnum = (int)$istrue;
	    if ($intnum>70) 
	    {
	    	return 101;
	    	$result["result"] = false;
			$result['message'] = "相似度大于70%";
			$this->ajaxReturn($result);
	    }else
	    {	
	    	return 100;
	    	$this->ajaxReturn(is_not('相似度小于70%'));
	    }	    
	}

	// faces_token 人脸对比
	public function faceauths($image_url=''){
		
		$user_id = get_user();
		$this->error_auths($user_id,'a');
		$image = I('post.image') ? I('post.image') : $this->ajaxReturn(is_not('image/必须'));
		// $image_url = A('Photo')->addImg($image);
		// $image_url = 'http://'.C('INT_COM').$image_url;
		// $image_url = 'http://www.next.zm-idea.com/Public/Uploads/weixin/11491060390.jpg';//
		// \Think\Log::record($image.'111111111111');
		$token = M('user')->where(array('id'=>$user_id))->getField('face_token');
		
		if (!$token) {
			$this->ajaxReturn(is_not('你还没有认证'));
		}
    	$url = 'https://api-cn.faceplusplus.com/facepp/v3/compare';
    	$data = array(
	        'api_key'       => $this->api_key,
	        'api_secret'    => $this->api_secret,
	        'image_url1'    => $image,
	        'face_token2'   => $token,
	        // 'image_base64'  => $image,
	    );

	    $res = curlGet($url,$data);
	    $res = json_decode($res);
	    // dump($res);exit();
	    $error_message = $res->error_message;
	    if ($error_message) 
	    {	
	    	$this->error_auth($user_id,'a');
	    	$this->ajaxReturn(is_not('网络出错'.$error_message));
	    }
	    // $istrue = $res->results[0]->confidence; // faceset 对比用的
	    $istrue = $res->confidence;
	    $intnum = (int)$istrue;
	    // \Think\Log::record($intnum);
	    if ($intnum>70) {
	    	$result["result"] = true;
			$result['message'] = "相似度大于70%";
			$this->ajaxReturn($result);
	    }else
	    {	
	    	$this->error_auth($user_id,'a');
	    	$this->ajaxReturn(is_not('相似度小于70%'));
	    }	    
	}

	// 获取faceset token 列表
	public function getfaceset(){
		$url = 'https://api-cn.faceplusplus.com/facepp/v3/faceset/getdetail';
    	$data = array(
	        'api_key'=>$this->api_key,
	        'api_secret'=>$this->api_secret,
	        'faceset_token'=>'553984c0c5e896ac325130967c46826b',
	    );

	    $res = curlGet($url,$data);
	    dump(json_decode($res));exit;
	    $res = json_decode($res)->error_message;
	}

	/**
	* 微信 图片下载 
	*/
	public function sendImage(){
		$user_id =get_user();
		$media_id=I('get.media_id');
		$is_identify=I('get.is_identify') ? I('get.is_identify') : 2;

		$token = A('Index')->gettoken();

		$url='http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.$token.'&media_id='.$media_id;

        $ch = curl_init($url);  
        curl_setopt($ch, CURLOPT_HEADER, 0);  
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头  
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
        $package = curl_exec($ch);  
        $httpinfo = curl_getinfo($ch);  
        curl_close($ch);  
          
        $prefix=explode("/", $httpinfo["content_type"]);
          
        $filename="Wx_Image".$user_id.time().".".$prefix[1];


        if ($is_identify == 1) 
        {	
        	
        	$local_file = fopen("Public/Uploads/active/".$filename, 'w'); 
	        $state=fwrite($local_file, $package);
	        fclose($local_file);
	        $filename = 'http://'.C('INT_COM').'/Public/Uploads/active/'.$filename;
        	// $this ->add_auth($filename);
        	// \Think\Log::record($filename.'5555555555555');
        }else
        {
        	
	        $local_file = fopen("Public/Uploads/weixin/".$filename, 'w'); 
	        $state=fwrite($local_file, $package);
	        fclose($local_file);
	        $filename = 'http://'.C('INT_COM').'/Public/Uploads/weixin/'.$filename;
        }

        $result["image_url"] = $filename;
		$result['status'] = 1;
		$this->ajaxReturn($result);
	    return $result;
	}
	// 微信照片过来对比  在info 测试用
	public function faceTouxiangs($image=''){
		$user_id = 125;//get_user();

		$image = 'http://www.next.zm-idea.com/Public/Uploads/weixin/Wx_Image1491629336.jpeg';//
		// $this->ajaxReturn(is_not($image_url));
		// $image_url='http://wx.qlogo.cn/mmopen/Iv8D5nD32icIFAmMo47ibhtxEJuYxPSdsGHrrbdPH6DIAQlYXCrHehjP5fDJGPxIrH6ict5XyeCxXIRpiaayMJROQg/0';

		$token = M('user')->where(array('id'=>$user_id))->getField('face_token');
		
		if (!$token) {
			$this->ajaxReturn(is_not('你还没有认证'));
		}
    	$url = 'https://api-cn.faceplusplus.com/facepp/v3/search';
    	$data = array(
	        'api_key'       => $this->api_key,
	        'api_secret'    => $this->api_secret,
	        'image_url'     => $image,
	        'faceset_token' => $token,
	        // 'image_base64'  => $image,
	    );

	    $res = curlGet($url,$data);
	    $res = json_decode($res);
	    // dump($res);exit();
	    $error_message = $res->error_message;
	    if ($error_message) 
	    {
			$result['intnum'] = '识别错误'.$error_message;
			$result['status'] = 110;

		    return $result;
	    }
	    $istrue = $res->results[0]->confidence;
	    $intnum = (int)$istrue;
	    
	    $result["image_url"] = $image_url;
		$result['intnum'] = $intnum;
		$result['status'] = 1;

	    return $result;	    
	}
	// faceset_token 对比 上传头像用 
	public function faceTouxiang($image){
		$user_id = get_user();

		$image_url = A('Photo')->addImg($image);
		$image_url = 'http://'.C('INT_COM').$image_url;
		// $image_url = 'http://www.next.zm-idea.com/Public/Uploads/active/11491060390.jpg';//

		$token = M('user')->where(array('id'=>$user_id))->getField('face_token');
		
		if (!$token) {
			$this->ajaxReturn(is_not('你还没有认证'));
		}
    	// $url = 'https://api-cn.faceplusplus.com/facepp/v3/search'; // 在faceset 对比
    	$url = 'https://api-cn.faceplusplus.com/facepp/v3/compare';  // 用User的token对比
    	$data = array(
	        'api_key'       => $this->api_key,
	        'api_secret'    => $this->api_secret,
	        'image_url1'    => $image_url,
	        'face_token2'   => $token,
	    );

	    $res = curlGet($url,$data);
	    $res = json_decode($res);
	    // dump($res);exit();
	    $error_message = $res->error_message;
	    if ($error_message) 
	    {
			$result['intnum'] = '识别错误'.$error_message;
			$result['status'] = 110;
		    return $result;
	    }
	    // $istrue = $res->results[0]->confidence; // faceset 对比用
	    $istrue = $res->confidence;
	    $intnum = (int)$istrue;
	    
	    $result["image_url"] = $image_url;
		$result['intnum'] = $intnum;
		$result['status'] = 1;

	    return $result;	    
	}
	// 第一张头像不加入后台，不去识别face
	public function addAuth(){
		$image = I('post.image') ? I('post.image') : $this->ajaxReturn(is_not('image/必须'));
		$this ->add_auth($image);

		$result["result"] = true;
		$result['message'] = "提交成功";
		$this->ajaxReturn($result);

	}
	// 认证头像加入后台
	public function add_auth($image)
	{	
		$user_id = get_user();
		if (!$image) 
		{
			$this->ajaxReturn(is_not('非法操作'));
		}
		$is_auth = M('user_auth')->field('user_id')->where(array('user_id'=>$user_id))->find();

		if ($is_auth) 
		{
			$data = M('user_auth')->where('user_id='.$user_id)->save(array('images'=>$image));
			M('user')->where('id='.$user_id)->save(array('is_verify'=>'1'));
		}
		else
		{
			$list= array(
				'add_time' => time(),
				'user_id'  => $user_id,
				'status'   => 0,
				'image'    => $image,
				);
			$data = M('user_auth')->add($list);
		}

		if (!$data) 
		{
			$this->ajaxReturn(is_not('加入图片的时候出现异常'));
		}else
		{
			return true;
		}
	}

	// admin 调用移除faceset 中的face token
	public function admin_remove($user_id){

		$faceset_token = M('user')->where(array('id'=>$user_id))->field('faceset_token_id,face_token')->find();

		
    	$url = 'https://api-cn.faceplusplus.com/facepp/v3/faceset/removeface';
    	$data = array(
	        'api_key'       => $this->api_key,
	        'api_secret'    => $this->api_secret,
	        'faceset_token' => M('face_config')->where(array('id'=>$faceset_token['faceset_token_id']))->getField('faceset'),
	        'face_tokens'   => $faceset_token['face_token'],
	        // 'image_base64'  => $image,
	    );

	    $res = curlGet($url,$data);
	    $res = json_decode($res);

	    $error_message = $res->error_message;
	    if ($error_message) 
	    {	
	    	$arr['results'] = false;
	    	$arr['message'] = '错误'.$error_message;
	    	return $arr;
	    }else
	    {	
	    	M('face_config')->where(array('id'=>$faceset_token['faceset_token_id']))->setDec('num');
	    	$arr['results'] = true;
	    	$arr['message'] = 'ok';
	    	return $arr;
	    }
	}

	public function error_auth($user_id,$a){
		if (S($a.'err'.$user_id)<C('AUTH_NUMBER')) 
		{
			S($a.'err'.$user_id,S($a.'err'.$user_id)+1,C('AUTH_NUMBER_TIME'));
		}else{
			$this->ajaxReturn(is_not('错误识别超过三次，请'.C('AUTH_NUMBER_TIMES').'小时后重试'));
		}
	}

	public function error_auths($user_id,$a){
		if (S($a.'err'.$user_id)>=C('AUTH_NUMBER')) 
		{
			$this->ajaxReturn(is_not('错误识别超过三次，请'.C('AUTH_NUMBER_TIMES').'小时后重试'));
		}
	}

	public function test(){
		$user_id = get_user();
		dump(S('aerr'.$user_id));
		dump(S('berr'.$user_id));
		dump(S('cerr'.$user_id));
	}
}